import { useState, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { 
  PieChart, 
  Search, 
  Eye, 
  Edit, 
  Trash2, 
  Calendar,
  BarChart3,
  LineChart,
  PieChart as PieChartIcon,
  TrendingUp,
  Filter,
  Save,
  X
} from 'lucide-react';
import { chartApi } from '@/services/api';
import { useToast } from '@/hooks/use-toast';
import type { Chart } from '@/types/api';

export function ChartsPage() {
  const navigate = useNavigate();
  const [charts, setCharts] = useState<Chart[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [editingChart, setEditingChart] = useState<Chart | null>(null);
  const [editForm, setEditForm] = useState({
    name: '',
    goal: '',
    chartType: ''
  });
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [editLoading, setEditLoading] = useState(false);
  const { toast } = useToast();

  const handleEditChart = (chart: Chart) => {
    setEditingChart(chart);
    setEditForm({
      name: chart.name || '',
      goal: chart.goal || '',
      chartType: chart.chartType || ''
    });
    setEditDialogOpen(true);
  };

  const handleSaveEdit = async () => {
    if (!editingChart || !editForm.name || !editForm.goal) {
      toast({
        title: "请填写完整信息",
        description: "图表名称和分析目标不能为空",
        variant: "destructive",
      });
      return;
    }

    setEditLoading(true);
    try {
      const response = await chartApi.editChart({
        id: editingChart.id,
        name: editForm.name,
        goal: editForm.goal,
        chartType: editForm.chartType
      });

      if (response.code === 0) {
        toast({
          title: "编辑成功",
          description: "图表信息已更新",
        });
        setEditDialogOpen(false);
        setEditingChart(null);
        loadCharts();
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "编辑失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    } finally {
      setEditLoading(false);
    }
  };

  useEffect(() => {
    loadCharts();
  }, [currentPage]);

  // 搜索防抖处理
  useEffect(() => {
    const timer = setTimeout(() => {
      if (currentPage !== 1) {
        setCurrentPage(1); // 搜索时重置到第一页
      } else {
        loadCharts();
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [searchTerm]);

  const loadCharts = async () => {
    setLoading(true);
    try {
      // 调用真实API获取当前用户的图表列表，支持搜索
      const response = await chartApi.listMyChartByPage({
        current: currentPage,
        pageSize: 8,
        name: searchTerm || undefined, // 如果有搜索词，传递给API
      });
      
      if (response.code === 0) {
        setCharts(response.data.records);
        setTotalPages(response.data.totalPage);
      } else {
        throw new Error(response.message);
      }
    } catch (error: any) {
      toast({
        title: "加载失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
      // 如果API调用失败，设置空数组
      setCharts([]);
      setTotalPages(1);
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (id: number) => {
    try {
      const response = await chartApi.deleteChart(id);
      if (response.code === 0) {
        toast({
          title: "删除成功",
          description: "图表已删除",
        });
        loadCharts();
      }
    } catch (error: any) {
      toast({
        title: "删除失败",
        description: error.message || "请稍后重试",
        variant: "destructive",
      });
    }
  };

  const handleViewChart = (id: number) => {
    navigate(`/chart/${id}`);
  };

  const getChartIcon = (chartType: string) => {
    switch (chartType) {
      case '柱状图':
        return <BarChart3 className="h-4 w-4" />;
      case '折线图':
        return <LineChart className="h-4 w-4" />;
      case '饼图':
        return <PieChartIcon className="h-4 w-4" />;
      default:
        return <TrendingUp className="h-4 w-4" />;
    }
  };

  const getStatusBadge = (status: string) => {
    switch (status) {
      case 'wait':
        return <Badge className="bg-gray-100 text-gray-800 hover:bg-gray-100">等待生成</Badge>;
      case 'running':
        return <Badge className="bg-blue-100 text-blue-800 hover:bg-blue-100">生成中</Badge>;
      case 'success':
        return <Badge className="bg-green-100 text-green-800 hover:bg-green-100">生成成功</Badge>;
      case 'failed':
        return <Badge className="bg-red-100 text-red-800 hover:bg-red-100">生成错误</Badge>;
      default:
        return <Badge variant="secondary">未知</Badge>;
    }
  };

  // 使用服务端搜索，不需要客户端过滤
  const filteredCharts = charts;

  return (
    <div className="p-6 space-y-6">
      {/* Header */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <PieChart className="h-8 w-8 text-blue-600" />
          <div>
            <h1 className="text-3xl font-bold text-gray-900">我的图表</h1>
            <p className="text-gray-600">管理和查看您创建的所有图表</p>
          </div>
        </div>
        
        {/* 搜索和筛选 */}
        <div className="flex items-center space-x-3">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 h-4 w-4" />
            <Input
              placeholder="搜索图表..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="pl-10 w-64"
            />
          </div>
          <Button variant="outline" size="sm">
            <Filter className="h-4 w-4 mr-2" />
            筛选
          </Button>
        </div>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <div className="p-2 bg-blue-100 rounded-lg">
                <BarChart3 className="h-4 w-4 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-gray-600">总图表数</p>
                <p className="text-2xl font-bold text-gray-900">{charts.length}</p>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <div className="p-2 bg-green-100 rounded-lg">
                <TrendingUp className="h-4 w-4 text-green-600" />
              </div>
              <div>
                <p className="text-sm text-gray-600">生成成功</p>
                <p className="text-2xl font-bold text-gray-900">
                  {charts.filter(c => c.status === 'success').length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <div className="p-2 bg-blue-100 rounded-lg">
                <Calendar className="h-4 w-4 text-blue-600" />
              </div>
              <div>
                <p className="text-sm text-gray-600">生成中</p>
                <p className="text-2xl font-bold text-gray-900">
                  {charts.filter(c => c.status === 'running').length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center space-x-2">
              <div className="p-2 bg-red-100 rounded-lg">
                <Trash2 className="h-4 w-4 text-red-600" />
              </div>
              <div>
                <p className="text-sm text-gray-600">生成错误</p>
                <p className="text-2xl font-bold text-gray-900">
                  {charts.filter(c => c.status === 'failed').length}
                </p>
              </div>
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 图表列表 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
        {filteredCharts.map((chart) => (
          <Card key={chart.id} className="hover:shadow-lg transition-shadow">
            <CardHeader className="pb-3">
              <div className="flex items-start justify-between">
                <div className="flex items-center space-x-2">
                  {getChartIcon(chart.chartType || '')}
                  <CardTitle className="text-lg truncate">{chart.name?.replace(/,$/, '') || '未命名图表'}</CardTitle>
                </div>
                {getStatusBadge(chart.status)}
              </div>
            </CardHeader>
            <CardContent className="space-y-4">
              <div>
                <p className="text-sm text-gray-600 mb-1">分析目标</p>
                <p className="text-sm text-gray-800 line-clamp-2">{chart.goal}</p>
              </div>
              
              <div>
                <p className="text-sm text-gray-600 mb-1">图表类型</p>
                <p className="text-sm text-gray-800">{chart.chartType?.replace(/,$/, '') || '未指定'}</p>
              </div>
              
              <div>
                <p className="text-sm text-gray-600 mb-1">创建时间</p>
                <p className="text-sm text-gray-800">{chart.createTime}</p>
              </div>
              
              {chart.status === 'success' && chart.genResult && (
                <div>
                  <p className="text-sm text-gray-600 mb-1">分析结果</p>
                  <p className="text-sm text-gray-800 line-clamp-2">{chart.genResult}</p>
                </div>
              )}
              
              {chart.status === 'failed' && chart.execMessage && (
                <div>
                  <p className="text-sm text-gray-600 mb-1">错误信息</p>
                  <p className="text-sm text-red-600 line-clamp-2">{chart.execMessage}</p>
                </div>
              )}
              
              <div className="flex space-x-2 pt-2">
                <Button 
                  size="sm" 
                  variant="outline" 
                  className="flex-1"
                  onClick={() => handleViewChart(chart.id)}
                >
                  <Eye className="h-4 w-4 mr-1" />
                  查看
                </Button>
                <Button 
                  size="sm" 
                  variant="outline" 
                  className="flex-1"
                  onClick={() => handleEditChart(chart)}
                >
                  <Edit className="h-4 w-4 mr-1" />
                  编辑
                </Button>
                <Button 
                  size="sm" 
                  variant="outline" 
                  onClick={() => handleDelete(chart.id)}
                  className="text-red-600 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="h-4 w-4" />
                </Button>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 分页 */}
      {totalPages > 1 && (
        <div className="flex justify-center space-x-2">
          <Button
            variant="outline"
            onClick={() => setCurrentPage(prev => Math.max(1, prev - 1))}
            disabled={currentPage === 1}
          >
            上一页
          </Button>
          <span className="flex items-center px-4 text-sm text-gray-600">
            第 {currentPage} 页，共 {totalPages} 页
          </span>
          <Button
            variant="outline"
            onClick={() => setCurrentPage(prev => Math.min(totalPages, prev + 1))}
            disabled={currentPage === totalPages}
          >
            下一页
          </Button>
        </div>
      )}

      {/* 编辑对话框 */}
      <Dialog open={editDialogOpen} onOpenChange={setEditDialogOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle className="flex items-center space-x-2">
              <Edit className="h-5 w-5 text-blue-600" />
              <span>编辑图表</span>
            </DialogTitle>
          </DialogHeader>
          <div className="space-y-4 py-4">
            <div className="space-y-2">
              <Label htmlFor="edit-name">图表名称</Label>
              <Input
                id="edit-name"
                value={editForm.name}
                onChange={(e) => setEditForm({ ...editForm, name: e.target.value })}
                placeholder="请输入图表名称"
              />
            </div>
            
            <div className="space-y-2">
              <Label htmlFor="edit-goal">分析目标</Label>
              <Textarea
                id="edit-goal"
                value={editForm.goal}
                onChange={(e) => setEditForm({ ...editForm, goal: e.target.value })}
                placeholder="请描述分析目标"
                className="min-h-[100px]"
              />
            </div>
            
            <div className="space-y-2">
              <Label>图表类型</Label>
              <Select value={editForm.chartType} onValueChange={(value) => setEditForm({ ...editForm, chartType: value })}>
                <SelectTrigger>
                  <SelectValue placeholder="请选择图表类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="柱状图">柱状图</SelectItem>
                  <SelectItem value="折线图">折线图</SelectItem>
                  <SelectItem value="饼图">饼图</SelectItem>
                  <SelectItem value="散点图">散点图</SelectItem>
                  <SelectItem value="雷达图">雷达图</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
          
          <div className="flex justify-end space-x-2">
            <Button
              variant="outline"
              onClick={() => setEditDialogOpen(false)}
              disabled={editLoading}
            >
              <X className="h-4 w-4 mr-2" />
              取消
            </Button>
            <Button
              onClick={handleSaveEdit}
              disabled={editLoading}
              className="bg-blue-600 hover:bg-blue-700"
            >
              {editLoading ? (
                <>
                  <div className="h-4 w-4 mr-2 animate-spin rounded-full border-2 border-white border-t-transparent" />
                  保存中...
                </>
              ) : (
                <>
                  <Save className="h-4 w-4 mr-2" />
                  保存
                </>
              )}
            </Button>
          </div>
        </DialogContent>
      </Dialog>
    </div>
  );
}
